package com.zrx.zrxpicturebackend.manager;

import cn.hutool.core.io.FileUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.zrx.zrxpicturebackend.config.CosClientConfig;
import com.zrx.zrxpicturebackend.exception.BusinessException;
import com.zrx.zrxpicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CosManager {
  
    @Resource
    private CosClientConfig cosClientConfig;
  
    @Resource  
    private COSClient cosClient;

    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 下载对象
     *
     * @param key 唯一键
     */
    public COSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }

    /**
     * 上传图片并生成webp图片
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult uploadWebpOnly(String key, File file) {
        // 先上传并生成webp
        PutObjectResult putObjectResult = putPictureObject(key, file);

        // 删除原图
        cosClient.deleteObject(cosClientConfig.getBucket(), key);

        // 返回上传结果
        return putObjectResult;
    }


    /**
     * 上传对象（附带图片信息）
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        // 对图片进行处理（获取基本信息也被视作为一种处理）
        PicOperations picOperations = new PicOperations();
        // 1 表示返回原图信息
        picOperations.setIsPicInfo(1);
        List<PicOperations.Rule> rules = new ArrayList<>();
        //图片进行压缩（webp格式）
        PicOperations.Rule rule = new PicOperations.Rule();
        String webpKey = FileUtil.mainName(key) + ".webp";
        rule.setFileId(webpKey);
        rule.setRule("imageMogr2/format/webp");
        rule.setBucket(cosClientConfig.getBucket());
        rules.add(rule);
        // 图片进行缩放
        if (file.length() > 1024 * 2){
            PicOperations.Rule thumbanailRule = new PicOperations.Rule();
            thumbanailRule.setBucket(cosClientConfig.getBucket());
            String thumbnailKey = FileUtil.mainName(key) + "_thumbnail" + FileUtil.getSuffix(key);
            thumbanailRule.setFileId(thumbnailKey);
            // 缩放规则
            thumbanailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>",128,128));
            rules.add(thumbanailRule);
        }
        // 构造处理参数
        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }


    // 上传文件 使用流方式提高效率
    public String uploadToCOS(MultipartFile multipartFile, String bucketName, String key) throws Exception {

        try (InputStream inputStream = multipartFile.getInputStream()) {
            // 元信息配置
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(multipartFile.getSize());
            metadata.setContentType(multipartFile.getContentType());

            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, metadata);

            // 上传文件
            cosClient.putObject(putObjectRequest);

            // 生成访问链接
            return "https://" + bucketName + ".cos." + cosClient.getClientConfig().getRegion().getRegionName()
                    + ".myqcloud.com/" + key;
        } finally {
            cosClient.shutdown();
        }
    }

    /**
     * 删除对象存储中的文件 去除域名
     *key
     */
    public void deleteObject(String key) {
        try {
            //去除域名
            key = key.replace(cosClientConfig.getHost(), "");
            cosClient.deleteObject(cosClientConfig.getBucket(), key);
            log.info("删除对象存储中的原图成功，文件名：{}", key);
        } catch (CosClientException e) {
            log.error("删除对象存储中的文件失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
    }



}
